package com.tfswue.dyq.service;

import com.tfswue.dyq.entity.Book;
import com.tfswue.dyq.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Set;

@Service
public class BookService {

    private final BookMapper bookMapper;
    private final RedisTemplate<String, Object> redisTemplate; // 使用 Object 类型

    private static final String CACHE_PREFIX = "book:";
    private static final Duration CACHE_TTL = Duration.ofHours(1);

    @Autowired
    public BookService(BookMapper bookMapper, RedisTemplate<String, Object> redisTemplate) {
        this.bookMapper = bookMapper;
        this.redisTemplate = redisTemplate;
    }

    public Book getBookById(Long id) {
        String key = CACHE_PREFIX + id;

        // 从缓存获取
        Object cachedBook = redisTemplate.opsForValue().get(key);
        if (cachedBook instanceof Book) {
            return (Book) cachedBook;
        }

        // 从数据库获取
        Book book = bookMapper.selectById(id);
        if (book != null) {
            redisTemplate.opsForValue().set(key, book, CACHE_TTL);
        }
        return book;
    }

    @Transactional
    public void addBook(Book book) {
        // 设置默认状态为可借
        book.setStatus(0);
        bookMapper.insert(book);

        // 清除所有图书缓存
        Set<String> keys = redisTemplate.keys(CACHE_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
